// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Buffers;
using System.Runtime.InteropServices;

namespace Letter.IO.Memorizer;

/// <summary>
/// Wraps an array allocated in the pinned object heap in a reusable block of managed memory
/// </summary>
internal sealed class MemoryPoolBlock<T> : IMemoryOwner<T>
{
    internal MemoryPoolBlock(PinnedBlockMemoryPool<T> pool, int length)
    {
        Pool = pool;

        T[] pinnedArray = null;
#if NETSTANDARD2_1
        pinnedArray = new T[length];
#elif NETCOREAPP
        pinnedArray = GC.AllocateUninitializedArray<T>(length, pinned: true);
#endif
        Memory = MemoryMarshal.CreateFromPinnedArray(pinnedArray, 0, pinnedArray.Length);
    }

    /// <summary>
    /// Back-reference to the memory pool which this block was allocated from. It may only be returned to this pool.
    /// </summary>
    public PinnedBlockMemoryPool<T> Pool { get; }

    public Memory<T> Memory { get; }

    public void Dispose()
    {
        Pool.Return(this);
    }
}